package main

import (
	"crypto/tls"
	"crypto/x509"
	"fmt"
	"io/ioutil"
	"net/http"
)

var (
	caCert     = "./gen_crypto/crypto-config/peerOrganizations/org2.demo.com/peers/peer0.org2.demo.com/tls/ca.crt"     // server's ca
	clientCert = "./gen_crypto/crypto-config/peerOrganizations/org1.demo.com/peers/peer0.org1.demo.com/tls/server.crt" // client's cert
	clientKey  = "./gen_crypto/crypto-config/peerOrganizations/org1.demo.com/peers/peer0.org1.demo.com/tls/server.key" // client's private key
)

func main() {
	client := client()

	resp, err := client.Get("https://peer0.org2.demo.com:12306/get?oid=123456")
	//resp, err := client.Get("https://10.10.9.49:12306")
	if err != nil {
		fmt.Println("Get error:", err)
		return
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	fmt.Println(string(body))
}

func client() (client *http.Client) {
	pool := x509.NewCertPool()

	addTrust(pool, caCert)

	cliCrt, err := tls.LoadX509KeyPair(clientCert, clientKey)
	if err != nil {
		fmt.Println("Loadx509keypair err:", err)
		return
	}

	tr := &http.Transport{
		TLSClientConfig: &tls.Config{
			RootCAs:      pool,
			Certificates: []tls.Certificate{cliCrt},
			// InsecureSkipVerify: true,
		},
	}
	client = &http.Client{Transport: tr}
	resp, err := client.Get("https://peer0.org2.demo.com:12306/get?oid=123")
	//resp, err := client.Get("https://10.10.9.49:12306")
	if err != nil {
		fmt.Println("Get error:", err)
		return
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	fmt.Println(string(body))
	return client
}

func addTrust(pool *x509.CertPool, path string) {
	aCrt, err := ioutil.ReadFile(path)
	if err != nil {
		fmt.Println("ReadFile err:", err)
		return
	}
	pool.AppendCertsFromPEM(aCrt)
}
